<template>
  <ion-page>
    <ion-header :translucent="true">
      <ion-toolbar>
        <ion-title>租房系统</ion-title>
        <ion-buttons slot="end">
          <ion-button @click="logout" fill="clear">
            <ion-icon :icon="logOutOutline"></ion-icon>
            退出
          </ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>

    <!-- 租客专用首页 -->
    <ion-content :fullscreen="true" v-if="userStore.currentRole === 'tenant'" class="tenant-content">
      <!-- 五月租房活动横幅 -->
      <div class="activity-banner">
        <div class="banner-content">
          <div class="banner-text">
            <h2>五月租房</h2>
            <h3>返现不停</h3>
            <p>成功出租最高返现4000元</p>
          </div>
          <div class="banner-image">
            <ion-icon :icon="homeOutline" size="large"></ion-icon>
          </div>
        </div>
      </div>

      <!-- 签到和余额卡片 -->
      <div class="balance-card">
        <div class="balance-info">
          <div class="balance-left">
            <div class="balance-label">今日可提现金额</div>
            <div class="balance-amount">1500.00元</div>
          </div>
          <div class="balance-right">
            <div class="status-label">交易状态</div>
            <div class="status-value">未结清</div>
          </div>
        </div>
        <ion-button @click="goToActivity" fill="solid" color="primary" class="checkin-btn">
          签到
        </ion-button>
      </div>

      <!-- 代扣计划标题 -->
      <div class="section-header">
        <h3>代扣计划</h3>
        <ion-button fill="clear" size="small" color="primary">
          更多
        </ion-button>
      </div>

      <!-- 代扣计划列表 -->
      <div class="deduction-list">
        <div class="deduction-item" v-for="item in deductionPlans" :key="item.id">
          <div class="deduction-icon">
            <ion-icon :icon="homeOutline" color="primary"></ion-icon>
          </div>
          <div class="deduction-info">
            <h4>{{ item.address }}</h4>
            <div class="deduction-meta">
              <span class="rent-amount">房租金额：{{ item.amount }}元</span>
              <span class="due-date">交租日期：{{ item.dueDate }}</span>
            </div>
            <div class="deduction-status">
              <ion-chip :color="item.status === 'active' ? 'success' : 'medium'">
                {{ item.status === 'active' ? '进行中' : '已暂停' }}
              </ion-chip>
            </div>
          </div>
          <div class="deduction-actions">
            <ion-button
              fill="outline"
              size="small"
              color="medium"
              @click="pauseDeduction(item)"
            >
              {{ item.status === 'active' ? '暂停代扣' : '恢复代扣' }}
            </ion-button>
            <ion-button
              fill="outline"
              size="small"
              color="warning"
              @click="payRent(item)"
            >
              交费
            </ion-button>
            <ion-button
              fill="solid"
              size="small"
              color="primary"
              @click="viewDetails(item)"
            >
              详情
            </ion-button>
          </div>
        </div>
      </div>
    </ion-content>

    <!-- 其他角色的首页内容 -->
    <ion-content :fullscreen="true" class="ion-padding" v-if="userStore.currentRole !== 'landlord' && userStore.currentRole !== 'tenant'">
      <ion-header collapse="condense">
        <ion-toolbar>
          <ion-title size="large">租房系统</ion-title>
        </ion-toolbar>
      </ion-header>

      <!-- 用户信息卡片 -->
      <ion-card class="user-card">
        <ion-card-content>
          <div class="user-info">
            <ion-avatar>
              <ion-icon :icon="personCircleOutline" size="large"></ion-icon>
            </ion-avatar>
            <div class="user-details">
              <h2>{{ userStore.user?.name }}</h2>
              <p>@{{ userStore.user?.username }}</p>
              <ion-chip :color="getRoleColor()" v-if="userStore.currentRole">
                <ion-icon :icon="getRoleIcon()"></ion-icon>
                <ion-label>{{ getRoleName() }}</ion-label>
              </ion-chip>
            </div>
          </div>
        </ion-card-content>
      </ion-card>

      <!-- 功能区域 -->
      <div class="features-section">
        <h3>功能菜单</h3>
        <div class="features-grid">
          <ion-card class="feature-card" v-if="hasPermission('manage_properties')">
            <ion-card-content>
              <ion-icon :icon="homeOutline" size="large" color="primary"></ion-icon>
              <h4>房源管理</h4>
              <p>管理房屋信息</p>
            </ion-card-content>
          </ion-card>

          <ion-card class="feature-card" v-if="hasPermission('search_properties')" @click="searchProperties">
            <ion-card-content>
              <ion-icon :icon="searchOutline" size="large" color="secondary"></ion-icon>
              <h4>房源搜索</h4>
              <p>查找合适房源</p>
            </ion-card-content>
          </ion-card>

          <ion-card class="feature-card" v-if="hasPermission('manage_rentals')">
            <ion-card-content>
              <ion-icon :icon="documentTextOutline" size="large" color="tertiary"></ion-icon>
              <h4>租赁管理</h4>
              <p>管理租赁合同</p>
            </ion-card-content>
          </ion-card>

          <ion-card class="feature-card" v-if="hasPermission('manage_users')">
            <ion-card-content>
              <ion-icon :icon="peopleOutline" size="large" color="warning"></ion-icon>
              <h4>用户管理</h4>
              <p>管理系统用户</p>
            </ion-card-content>
          </ion-card>

          <ion-card class="feature-card" v-if="hasPermission('view_reports')">
            <ion-card-content>
              <ion-icon :icon="barChartOutline" size="large" color="success"></ion-icon>
              <h4>数据报表</h4>
              <p>查看统计报表</p>
            </ion-card-content>
          </ion-card>

          <ion-card class="feature-card" v-if="hasPermission('view_profile')">
            <ion-card-content>
              <ion-icon :icon="settingsOutline" size="large" color="medium"></ion-icon>
              <h4>个人设置</h4>
              <p>管理个人信息</p>
            </ion-card-content>
          </ion-card>
        </div>
      </div>
    </ion-content>

    <!-- 房东专用首页 -->
    <ion-content :fullscreen="true" v-if="userStore.currentRole === 'landlord'" class="landlord-content">

      <!-- 五月租房活动横幅 -->
      <div class="activity-banner">
        <div class="banner-content">
          <div class="banner-text">
            <h2>五月租房</h2>
            <h3>返现不停</h3>
            <p>成功出租最高返现4000元</p>
          </div>
          <div class="banner-image">
            <ion-icon :icon="homeOutline" size="large"></ion-icon>
          </div>
        </div>
      </div>

      <!-- 快捷操作按钮 -->
      <div class="quick-actions">
        <div class="action-row">
          <div class="action-item" @click="goToLandlordVerification">
            <ion-icon :icon="shieldCheckmarkOutline" color="success"></ion-icon>
            <span>房东认证</span>
          </div>
          <div class="action-item" @click="publishProperty">
            <ion-icon :icon="addCircleOutline" color="primary"></ion-icon>
            <span>发布房源</span>
          </div>
        </div>
        <div class="action-row">
          <div class="action-item" @click="goToQRCode">
            <ion-icon :icon="qrCodeOutline" color="primary"></ion-icon>
            <span>机器二维码</span>
          </div>
          <div class="action-item" @click="manageProperties">
            <ion-icon :icon="homeOutline" color="primary"></ion-icon>
            <span>房源管理</span>
          </div>
        </div>
      </div>

      <!-- 数据统计卡片 -->
      <div class="stats-section">
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-number">{{ stats.members }}</div>
            <div class="stat-label">中介成员</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ stats.totalProperties }}</div>
            <div class="stat-label">门店房源</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ stats.rentedProperties }}</div>
            <div class="stat-label">已出租房源</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ stats.availableProperties }}</div>
            <div class="stat-label">未出租房源</div>
          </div>
        </div>
      </div>

      <!-- 我的房源列表 -->
      <div class="my-properties">
        <div class="section-header">
          <h3>我的房源</h3>
          <ion-button fill="clear" size="small" @click="viewAllProperties">
            更多
          </ion-button>
        </div>

        <div class="properties-list" v-if="myProperties.length > 0">
          <ion-card v-for="property in myProperties" :key="property.id" class="property-card">
            <ion-card-content>
              <div class="property-info">
                <h4>{{ property.title }}</h4>
                <p>{{ property.address }}</p>
                <div class="property-meta">
                  <span class="price">¥{{ property.price }}/月</span>
                  <ion-chip :color="property.status === 'available' ? 'success' : 'medium'">
                    {{ property.status === 'available' ? '可租' : '已租' }}
                  </ion-chip>
                </div>
              </div>
            </ion-card-content>
          </ion-card>
        </div>

        <div class="empty-state" v-else>
          <ion-icon :icon="homeOutline" size="large" color="medium"></ion-icon>
          <p>您还没有发布房源信息</p>
          <ion-button @click="publishProperty" fill="outline">
            立即发布
          </ion-button>
        </div>
      </div>

      <!-- 服务协议浮动按钮 -->
      <ion-fab vertical="bottom" horizontal="end" slot="fixed">
        <ion-fab-button @click="goToServiceAgreement" color="primary">
          <ion-icon :icon="documentTextOutline"></ion-icon>
        </ion-fab-button>
      </ion-fab>
    </ion-content>
  </ion-page>
</template>

<script setup lang="ts">

import { useRouter } from 'vue-router'
import {
  IonContent,
  IonHeader,
  IonPage,
  IonTitle,
  IonToolbar,
  IonButtons,
  IonButton,
  IonIcon,
  IonCard,
  IonCardContent,
  IonAvatar,
  IonChip,
  IonLabel,

  alertController,
  toastController
} from '@ionic/vue'
import {
  personCircleOutline,
  logOutOutline,
  homeOutline,
  searchOutline,
  documentTextOutline,
  peopleOutline,
  barChartOutline,
  settingsOutline,
  shieldCheckmarkOutline,
  addCircleOutline,
  qrCodeOutline
} from 'ionicons/icons'
import { useUserStore } from '@/stores/user'
import { usePropertyStore } from '@/stores/property'
import { computed, ref } from 'vue'

const router = useRouter()
const userStore = useUserStore()
const propertyStore = usePropertyStore()

// 租客代扣计划数据
interface DeductionPlan {
  id: string
  address: string
  amount: number
  dueDate: string
  status: 'active' | 'paused'
}

const deductionPlans = ref<DeductionPlan[]>([
  {
    id: '1',
    address: '临沂外滩10号楼603',
    amount: 1500.00,
    dueDate: '每月01日',
    status: 'active'
  },
  {
    id: '2',
    address: '临沂外滩10号楼603',
    amount: 1500.00,
    dueDate: '每月01日',
    status: 'active'
  }
])

// 房东数据统计
const stats = computed(() => {
  if (!userStore.user?.id) {
    return {
      members: 1,
      totalProperties: 0,
      rentedProperties: 0,
      availableProperties: 0
    }
  }

  const propertyStats = propertyStore.getPropertyStats(userStore.user.id.toString())
  return {
    members: 1,
    totalProperties: propertyStats.total,
    rentedProperties: propertyStats.rented,
    availableProperties: propertyStats.available
  }
})

// 我的房源列表
const myProperties = computed(() => {
  if (!userStore.user?.id) return []
  return propertyStore.getPropertiesByLandlord(userStore.user.id.toString())
})



// 角色权限映射
const rolePermissions: Record<string, string[]> = {
  admin: ['manage_users', 'manage_properties', 'manage_rentals', 'view_reports'],
  landlord: ['manage_properties', 'view_rentals', 'manage_tenants'],
  tenant: ['search_properties', 'manage_rentals', 'view_profile']
}

// 检查权限
const hasPermission = (permission: string) => {
  if (!userStore.currentRole) return false
  return rolePermissions[userStore.currentRole]?.includes(permission) || false
}

// 获取角色名称
const getRoleName = () => {
  const roleNames: Record<string, string> = {
    admin: '管理员',
    landlord: '房东',
    tenant: '租客'
  }
  return roleNames[userStore.currentRole || ''] || userStore.currentRole
}

// 获取角色颜色
const getRoleColor = () => {
  const colors: Record<string, string> = {
    admin: 'danger',
    landlord: 'warning',
    tenant: 'primary'
  }
  return colors[userStore.currentRole || ''] || 'medium'
}

// 获取角色图标
const getRoleIcon = () => {
  const icons: Record<string, any> = {
    admin: shieldCheckmarkOutline,
    landlord: homeOutline,
    tenant: peopleOutline
  }
  return icons[userStore.currentRole || ''] || personCircleOutline
}

// 跳转到房东认证页面
const goToLandlordVerification = () => {
  router.push('/landlord-verification')
}

// 跳转到服务协议页面
const goToServiceAgreement = () => {
  router.push('/service-agreement')
}
// 发布房源
const publishProperty = () => {
  router.push('/publish-property')
}

// 跳转到二维码页面
const goToQRCode = () => {
  router.push('/qrcode')
}



// 查看所有房源
const viewAllProperties = () => {
  // 跳转到房源管理页面
  console.log('查看所有房源')
}

// 房源管理
const manageProperties = async () => {
  const toast = await toastController.create({
    message: '房源管理功能开发中...',
    duration: 2000,
    color: 'primary',
    position: 'top'
  })
  await toast.present()
}

// 跳转到活跃度页面（签到功能）
const goToActivity = () => {
  router.push('/activity')
}

// 暂停/恢复代扣
const pauseDeduction = async (item: DeductionPlan) => {
  const newStatus = item.status === 'active' ? 'paused' : 'active'
  const actionText = newStatus === 'paused' ? '暂停' : '恢复'

  const alert = await alertController.create({
    header: `确认${actionText}代扣`,
    message: `确定要${actionText}${item.address}的代扣计划吗？`,
    buttons: [
      {
        text: '取消',
        role: 'cancel'
      },
      {
        text: '确定',
        handler: () => {
          item.status = newStatus
          showToast(`已${actionText}代扣计划`)
        }
      }
    ]
  })
  await alert.present()
}

// 交费功能
const payRent = async (item: DeductionPlan) => {
  const alert = await alertController.create({
    header: '确认交费',
    message: `确定要为${item.address}交费${item.amount}元吗？`,
    buttons: [
      {
        text: '取消',
        role: 'cancel'
      },
      {
        text: '确定',
        handler: () => {
          showToast('交费功能开发中...')
        }
      }
    ]
  })
  await alert.present()
}

// 查看详情
const viewDetails = async (item: DeductionPlan) => {
  const alert = await alertController.create({
    header: '代扣详情',
    message: `
      地址：${item.address}
      金额：${item.amount}元
      交租日期：${item.dueDate}
      状态：${item.status === 'active' ? '进行中' : '已暂停'}
    `,
    buttons: ['确定']
  })
  await alert.present()
}

// 房源搜索
const searchProperties = async () => {
  const toast = await toastController.create({
    message: '房源搜索功能开发中...',
    duration: 2000,
    color: 'primary',
    position: 'top'
  })
  await toast.present()
}

// 显示提示消息
const showToast = async (message: string) => {
  const toast = await toastController.create({
    message,
    duration: 2000,
    color: 'success',
    position: 'top'
  })
  await toast.present()
}

// 退出登录
const logout = async () => {
  const alert = await alertController.create({
    header: '确认退出',
    message: '确定要退出登录吗？',
    buttons: [
      {
        text: '取消',
        role: 'cancel'
      },
      {
        text: '确定',
        handler: () => {
          userStore.logout()
          router.replace('/login')
        }
      }
    ]
  })
  await alert.present()
}
</script>

<style scoped>
.user-card {
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-info ion-avatar {
  width: 60px;
  height: 60px;
}

.user-details h2 {
  margin: 0 0 4px 0;
  color: var(--ion-color-dark);
}

.user-details p {
  margin: 0 0 8px 0;
  color: var(--ion-color-medium);
  font-size: 14px;
}

.features-section h3 {
  margin: 20px 0 16px 0;
  color: var(--ion-color-dark);
  font-weight: 600;
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 12px;
}

.feature-card {
  cursor: pointer;
  transition: transform 0.2s ease;
  margin: 0;
}

.feature-card:hover {
  transform: translateY(-2px);
}

.feature-card ion-card-content {
  text-align: center;
  padding: 16px;
}

.feature-card h4 {
  margin: 8px 0 4px 0;
  color: var(--ion-color-dark);
  font-size: 14px;
}

.feature-card p {
  margin: 0;
  color: var(--ion-color-medium);
  font-size: 12px;
}

/* 房东首页样式 */
.landlord-content {
  --background: white;
}

.landlord-header {
  background: white;
  padding: 16px;
  margin: -16px -16px 16px -16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.welcome-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-text {
  color: var(--ion-color-dark);
  font-size: 16px;
  font-weight: 500;
}

.switch-role-btn {
  --color: var(--ion-color-primary);
  --background: rgba(79, 172, 254, 0.1);
  --border-radius: 16px;
  height: 32px;
  font-size: 12px;
}

.activity-banner {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  border-radius: 16px;
  padding: 20px;
  margin: 12px 0 16px 0;
  color: white;
  position: relative;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(79, 172, 254, 0.3);
  transform: translateY(-8px);
}

.banner-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.banner-text h2 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.banner-text h3 {
  margin: 4px 0;
  font-size: 20px;
  font-weight: 600;
}

.banner-text p {
  margin: 8px 0 0 0;
  font-size: 14px;
  opacity: 0.9;
}

.banner-image {
  font-size: 48px;
  opacity: 0.3;
}

.quick-actions {
  margin-bottom: 24px;
  padding: 0 4px;
}

.action-row {
  display: flex;
  gap: 12px;
  justify-content: space-between;
  margin-bottom: 12px;
}

.action-row:last-child {
  margin-bottom: 0;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 20px 16px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  flex: 1;
  border: 1px solid rgba(0, 0, 0, 0.04);
}

.action-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
}

.action-item:active {
  transform: translateY(-2px);
  transition: all 0.1s ease;
}

.action-item ion-icon {
  font-size: 32px;
}

.action-item span {
  font-size: 14px;
  color: var(--ion-color-dark);
  font-weight: 500;
}

.stats-section {
  margin-bottom: 24px;
  padding: 0 4px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1px;
  background: rgba(0, 0, 0, 0.06);
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.stat-item {
  background: white;
  padding: 20px 8px;
  text-align: center;
  transition: background-color 0.2s ease;
}

.stat-item:hover {
  background: rgba(79, 172, 254, 0.02);
}

.stat-number {
  font-size: 20px;
  font-weight: bold;
  color: var(--ion-color-primary);
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: var(--ion-color-medium);
}

.my-properties {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-header h3 {
  margin: 0;
  color: var(--ion-color-dark);
  font-weight: 600;
}

.properties-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.property-card {
  margin: 0;
}

.property-info h4 {
  margin: 0 0 4px 0;
  color: var(--ion-color-dark);
  font-size: 16px;
}

.property-info p {
  margin: 0 0 8px 0;
  color: var(--ion-color-medium);
  font-size: 14px;
}

.property-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 16px;
  font-weight: bold;
  color: var(--ion-color-danger);
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: var(--ion-color-medium);
}

.empty-state ion-icon {
  margin-bottom: 16px;
}

.empty-state p {
  margin: 0 0 16px 0;
  font-size: 14px;
}

/* 租客首页样式 */
.tenant-content {
  --background: #f5f5f5;
  padding: 0;
}

.tenant-content .activity-banner {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  border-radius: 0 0 20px 20px;
  padding: 20px;
  margin: 0 0 16px 0;
  color: white;
  position: relative;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(79, 172, 254, 0.3);
}

.balance-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 20px;
  margin: 0 16px 20px 16px;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
}

.balance-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.balance-left .balance-label {
  font-size: 12px;
  opacity: 0.8;
  margin-bottom: 4px;
}

.balance-left .balance-amount {
  font-size: 20px;
  font-weight: bold;
}

.balance-right {
  text-align: right;
}

.balance-right .status-label {
  font-size: 12px;
  opacity: 0.8;
  margin-bottom: 4px;
}

.balance-right .status-value {
  font-size: 14px;
  font-weight: 500;
}

.checkin-btn {
  --background: rgba(255, 255, 255, 0.2);
  --color: white;
  --border-radius: 20px;
  height: 40px;
  margin-left: 16px;
  backdrop-filter: blur(10px);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px;
  margin-bottom: 12px;
}

.section-header h3 {
  margin: 0;
  color: var(--ion-color-dark);
  font-weight: 600;
  font-size: 16px;
}

.deduction-list {
  padding: 0 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.deduction-item {
  background: white;
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.deduction-icon {
  width: 40px;
  height: 40px;
  background: rgba(79, 172, 254, 0.1);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.deduction-icon ion-icon {
  font-size: 20px;
}

.deduction-info {
  flex: 1;
  min-width: 0;
}

.deduction-info h4 {
  margin: 0 0 8px 0;
  color: var(--ion-color-dark);
  font-size: 16px;
  font-weight: 600;
}

.deduction-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-bottom: 8px;
}

.deduction-meta span {
  font-size: 14px;
  color: var(--ion-color-medium);
}

.rent-amount {
  font-weight: 500;
  color: var(--ion-color-dark) !important;
}

.deduction-status {
  margin-bottom: 12px;
}

.deduction-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex-shrink: 0;
}

.deduction-actions ion-button {
  --height: 32px;
  --padding-start: 12px;
  --padding-end: 12px;
  font-size: 12px;
  min-width: 70px;
}
</style>
